import Taro from '@tarojs/taro'
import { Component } from 'react'
import { View, Image } from '@tarojs/components'
import { connect } from 'react-redux'

import './index.scss'

@connect(state => state.app)
class LdPage extends Component {
  state = {
    pageLoading: false,
    isTab: false,
  }

  componentDidMount() {
    const isTab = this.checkIsTab()
    this.setState({ isTab })
    const { onRef } = this.props
    if (onRef) {
      onRef(this)
    } else {
      this.setState({ pageLoading: true })
    }
  }

  checkIsTab() {
    const route = Taro.getCurrentInstance().page.route
    const tabList = Taro.getCurrentInstance().app.config.tabBar.list
    return tabList.some(t => t.pagePath === route)
  }

  async pageInit(fun) {
    // 等待用户信息加载完成
    const { userInfo } = this.props
    if (!userInfo._id) {
      setTimeout(async () => {
        this.pageInit(fun)
      }, 200)
      return
    }

    // 执行页面方法
    await fun?.()

    // 关闭加载
    setTimeout(() => {
      this.setState({ pageLoading: true })
    }, 0)
  }

  render() {
    const { layout:{ safeArea_bottom } } = this.props
    const { pageLoading, isTab } = this.state
    return (
      <View className='LdPage' style={{ paddingBottom: isTab?0:safeArea_bottom }}>
        {!pageLoading && <View className='loading'>
          <Image className='loading-img' src='https://qn-qghotel.lindingtechnology.com/pcenter_1605168564015' />
        </View>}
        {pageLoading && this.props.children }
      </View>
    )
  }
}

export default LdPage
